package com.gxa.shop.dao.favorite.Impl;

import com.gxa.shop.bean.pojo.Favorite;
import com.gxa.shop.bean.vo.FavoriteVo;
import com.gxa.shop.commons.jdbc.JDBCUtil;
import com.gxa.shop.dao.favorite.FavoriteDao;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * com.gxa.shop.dao.favorite.Impl
 * User: 刁彦侨
 * Date: 2024/12/23 10:42
 * motto:   逆水行舟不进则退
 * Description:
 * Version: V1.0
 */
public class FavoriteDaoImpl implements FavoriteDao {
    @Override
    public List<FavoriteVo> findById(String id) {
        String sql = "SELECT f.user_id, p.product_id, p.product_name, p.product_image, p.product_color, p.unit_price FROM favorite f JOIN product p ON f.product_id = p.product_id WHERE f.user_id = ?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        List<Map<String, Object>> query = jdbcUtil.query(sql.toString(), id);
        if(query.size()>0){
            List<FavoriteVo> favorites = new ArrayList<>();
            for (Map<String, Object> row : query) {
                FavoriteVo favoriteVo = new FavoriteVo();
                favoriteVo.setUserId((Integer) row.get("user_id"));
                favoriteVo.setProductId((Integer) row.get("product_id"));
                favoriteVo.setProductName((String) row.get("product_name"));
                favoriteVo.setProductImage((String) row.get("product_image"));
                favoriteVo.setProductColor((String) row.get("product_color"));
                favoriteVo.setUnitPrice((Double) row.get("unit_price"));
                favorites.add(favoriteVo);
            }
            System.out.println("收藏夹查询成功");
            return favorites;
        }
        System.out.println("收藏夹为空");
        return null;
    }

    @Override
    public int insert(Favorite favorite) {
        String sql = "INSERT INTO favorite(user_id, product_id) VALUES (?, ?)";
        JDBCUtil jdbcUtil = new JDBCUtil();
        List<Object> parameters=new ArrayList<>();
        parameters.add(favorite.getUserId());
        parameters.add(favorite.getProductId());
        return jdbcUtil.update(sql,parameters.toArray());
    }

    @Override
    public int deleteById(Integer userId, Integer productId) {
        String sql = "DELETE FROM favorite WHERE user_id = ? AND product_id = ?";
        JDBCUtil jdbcUtil = new JDBCUtil();
        return jdbcUtil.update(sql, userId, productId);
    }
}
